<template>
	<view style="padding: 40rpx;">
		<view style="padding: 20rpx; margin: 80rpx 0; background-color: #fff; box-shadow: 0 2rpx 10rpx rgba(0,0,0,.1); border-radius: 10rpx;">
			<view style="margin: 50rpx 30rpx; font-size: 40rpx;">欢迎注册</view>
			<uni-forms ref="form" :modelValue="form" :rules="rules" validateTrigger='blur'>
				<uni-forms-item name="account" required>
					<uni-easyinput prefixIcon="person" v-model="form.account" placeholder="请输入账号" />
				</uni-forms-item>
				<uni-forms-item name="password" required>
					<uni-easyinput type="password" prefixIcon="locked" v-model="form.password" placeholder="请输入密码" />
				</uni-forms-item>
				<!-- 新增家长和教师角色选择 -->
				<view style="margin: 10px; margin-bottom: 20px;">
				  <uv-radio-group v-model="form.role" placement="row">
				    <uv-radio name="user" label="家长"></uv-radio>
				    <uv-radio name="teacher" activeColor="red" label="教师"></uv-radio>
				  </uv-radio-group>
				</view>
				<uni-forms-item>
					<button @click="register" style="background-color: #ffd100; border-color: #ffd100; height: 70rpx; line-height: 70rpx;">注 册</button>
				</uni-forms-item>
				<uni-forms-item>
					<view style="text-align: right;">已有账号？去 
						<navigator style="display: inline-block; color: dodgerblue; margin-left: 4rpx;" url="/pages/login/login">登录</navigator>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					account: '',
					password: '',
					role: 'user' // 默认为家长
				},
				rules: {
					// 对 username 字段进行必填验证
					account: {
						rules:[
							{ required: true, errorMessage: '请输入账号' },
							{ minLength: 3, maxLength: 10, errorMessage: '账号长度在 {minLength} 到 {maxLength} 个字符' }
						]
					},
					password: {
						rules:[
							{ required: true, errorMessage: '请输入密码' },
							{ minLength: 3, maxLength: 10, errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符' }
						]
					}
				}
			}
		},
		methods: {
			register() {
				this.$refs.form.validate().then(res => {
					// 根据角色来选择不同的注册接口
					const registerUrl = this.form.role === 'teacher' ? '/teacher/add' : '/user/add';

					this.$request.post(registerUrl, this.form).then(res => {
						if (res.code === '200') {
							uni.showToast({
								icon: 'success',
								title: '注册成功'
							});
							
							setTimeout(() => {
								// 跳转到登录页面
								uni.navigateTo({
									url: '/pages/login/login'
								});
							}, 500);
						} else {
							uni.showToast({
								icon: 'error',
								title: res.msg || '注册失败'
							});
						}
					}).catch(err => {
						uni.showToast({
							icon: 'error',
							title: '请求失败，请稍后重试'
						});
						console.error('请求错误：', err);
					});
				}).catch(err => {
					console.log('表单错误信息：', err);
				});
			}
		}
	}
</script>

<style>
/* 添加样式可以根据需要自行扩展 */
</style>
